package com.sailors.common.task.provider.infra.design.common.util;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sailors.common.task.provider.faced.model.dto.execute.ExcelUploadDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Excel util
 *
 * @description: excel工具
 * @author: cyj
 * @date 2023 -04-15 10:51:47
 */
@Slf4j
public final class ExcelUtil {

    /**
     * 将excelUploadDto写到outputStream
     * @param outputStream
     * @param excelUploadDto
     */
    public static void write2OutputStream(ByteArrayOutputStream outputStream, ExcelUploadDto excelUploadDto) {
        EasyExcel.write(outputStream)
                .head(head(excelUploadDto.getExcelHeads()))
                .sheet("auto_" + IdWorker.get32UUID())
                .doWrite(dataList(excelUploadDto.getExcelRows(), excelUploadDto.getExcelHeads()));
    }

    /**
     * 转换list数据
     *
     * @return
     */
    private static List<List<Object>> dataList(LinkedList<JSONObject> excelRows, LinkedList<String> excelHeads) {
        List<List<Object>> dates = new ArrayList<>();

        excelRows.forEach(excelRow -> {
            List<Object> row = new LinkedList<>();
            excelHeads.forEach(exceHead -> row.add(excelRow.get(exceHead)));
            dates.add(row);
        });

        return dates;
    }

    /**
     * 设置Excel头
     * @param headList  Excel头信息
     * @return
     */
    private static List<List<String>> head(List<String> headList) {
        return headList.stream().map(headStr -> CollectionUtil.newArrayList(headStr)).collect(Collectors.toList());
    }
}